package org.itboys.mongodb.service;


import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.mongodb.entity.BaseMySqlEntity;
import org.itboys.mysql.dao.BaseMySqlMapper;
import org.itboys.param.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月8日
 * 联系方式 ：empty90911@126.com
 * 描述：mysql业务层，基础Service。需要倒入baseMysqlMapper
 *
 */
@Service
public abstract class BaseMySqlService<T extends BaseMySqlEntity>{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired 
	protected BaseMySqlMapper<T> baseMySqlMapper;
	/**
	 * 查询
	 * @param param
	 * @return
	 */
	public List<T> select(Map<String,Object> param){
		return baseMySqlMapper.select(param);
	}

	/**
	 * 统计行数
	 * @param param
	 * @return
	 */
	public long count(Map<String,Object> param){
		Serializable count = baseMySqlMapper.count(param);
		if(count==null){
			return 0L;
		}else{
			return Long.valueOf(count.toString());
		}
	}
	/**
	 * 查询。封装分页结果
	 * @param param
	 * @return
	 */
	public PageResult<T> selectPage(Map<String,Object> param) {
		return new PageResult<T>(select(param),count(param));
	}

	/**
	 * 删除
	 * @param id
	 */
	public void delete(Long id){
		baseMySqlMapper.delete(id);
	}

	/**
	 * 新增
	 * @param t
	 */
	public void insert(T t){

		if(AdminSessionHolder.getAdminUserId()!=null&&AdminSessionHolder.getAdminUserId().longValue()!=0l){
			t.setCreator(AdminSessionHolder.getAdminUserId());
		}else{
			t.setCreator(0l);
		}


		if(AdminSessionHolder.getAdminUserId()!=null&&AdminSessionHolder.getAdminUserId().longValue()!=0l){
			t.setUpdater(AdminSessionHolder.getAdminUserId());
		}else{
			t.setUpdater(0l);
		}

		baseMySqlMapper.insert(t);
	}

	/**
	 * 修改
	 * @param t
	 */
	public void update(T t){

		long now = System.currentTimeMillis();

		//设置姓名。待补充
		if(AdminSessionHolder.getAdminUserId()!=null&&AdminSessionHolder.getAdminUserId().longValue()!=0l){
			t.setUpdater(AdminSessionHolder.getAdminUserId());
		}else{
			t.setUpdater(0l);
		}
		//设置姓名。待补充


		baseMySqlMapper.update(t);
	}

	/**
	 * 单个查询
	 * @param id
	 * @return
	 */
	public T find(long id){
		return baseMySqlMapper.find(id);
	}


}
